﻿#region imports

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using Codeplex.ODataTFS.Model.Entities;

#endregion

namespace Codeplex.ODataTFS.Model.Serialization
{
	public class TFSLinkProxy : TFSBaseProxy
	{
		public TFSLinkProxy(Uri uri, ICredentials credentials)
			: base(uri, credentials)
		{
		}

		public IEnumerable<Link> GetLinksByWorkItem(int workItemId)
		{
			var key = string.Format(CultureInfo.InvariantCulture, "TFSWorkItemProxy.GetLinksByWorkItem_{0}", workItemId);

			if (Cache[key] == null)
			{
				Cache[key] = RequestLinksByWorkItem(workItemId);
			}

			return (IEnumerable<Link>) Cache[key];
		}

		private IEnumerable<Link> RequestLinksByWorkItem(int workItemId)
		{
			var wiql = string.Format(CultureInfo.InvariantCulture, "SELECT [System.Id] FROM WorkItems WHERE [System.Id] = {0}", workItemId);

			var workItemServer = TfsConnection.GetService<Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore>();

			var wiColl = QueryWorkItems(wiql);
			if (wiColl.Count == 0)
			{
				return new List<Link>();
			}

			List<Link> linkColl = wiColl[0].Links
				.Cast<Microsoft.TeamFoundation.WorkItemTracking.Client.Link>()
				.Select(l => l.ToModel(workItemServer, workItemId)).ToList();

			foreach (var l in linkColl)
			{
				if (l.BaseLinkType == Microsoft.TeamFoundation.WorkItemTracking.Client.BaseLinkType.ExternalLink.ToString())
				{
					l.LinkedArtifactUri =
						GetTfsWebAccessArtifactUrl(new Uri(l.LinkedArtifactUri)).ToString();
				}
			}

			return linkColl;
		}
	}
}
